package forum.service.rpc;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.foreveross.springboot.dubbo.utils.Payload;
import forum.domain.Resources;
import forum.domain.Role;
import forum.domain.RoleResources;
import forum.domain.UserRole;
import forum.repository.ResourcesRepository;
import forum.repository.RoleRepository;
import forum.repository.RoleResourcesRepository;
import forum.service.rpc.api.RoleResourcesService;
import forum.service.tools.BaseSearch;
import forum.service.tools.SearchDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/4/5.
 */
@org.springframework.stereotype.Service("roleResourcesService")
public class RoleResourcesServiceImpl implements RoleResourcesService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RoleResourcesRepository roleResourcesRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private ResourcesRepository resourcesRepository;


    public Object getRoleResourcesListByRolename(@QueryParam("rolename") @DefaultValue("rolename=admin") String rolename) {
        List<RoleResources> list = new ArrayList();
        list = roleResourcesRepository.findByRolename(rolename);
        return list;
    }

    public Object getRoleResourcesList(@QueryParam("page") @DefaultValue("0") int page,
                                       @QueryParam("size") @DefaultValue("50") int size,
                                       @QueryParam("sort") @DefaultValue("sort=roleresourcesid,desc") String sort,
                                       @QueryParam("operation") @DefaultValue("operation=eq") String operation,
                                       @QueryParam("key") @DefaultValue("key=roleresourcesid") String key,
                                       @QueryParam("value") @DefaultValue("1") String value) {
//        logger.debug("get roles: {} . -> {}", "GET /api/v1/roles/", sort);

        // 简单适配, 暂无严谨性
        sort = sort.replaceAll("sort=", "").trim(); // sort=firstname,desc
        String[] sort_arr = sort.split(",");
        Sort.Direction direction;
        if (sort_arr[1] != null && "desc".equals(sort_arr[1])) {
            direction = Sort.Direction.DESC;
        } else {
            direction = Sort.Direction.ASC;
        }
        String[] properties = sort_arr[0].split("&");

        Sort _sort = new Sort(direction, Arrays.asList(properties));
        Pageable pageable = new PageRequest(page, size, _sort);

        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(operation) || StringUtils.isEmpty(value)) {
            logger.info("提示: key或者operation或者value为空 ");

        }

        if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(operation) && !StringUtils.isEmpty(value)) {
            logger.info("提示: key并且operation并且value都不为空 ");
//            return roleResourcesRepository.findAll(new BaseSearch<Resources>(new SearchDto(key,operation, value)),pageable);
            return "提示: key并且operation并且value都不为空 ";
        }

        return roleResourcesRepository.findAll(pageable);

    }


    public Object getResourcesListByRolename(String rolename) {

        List<Resources> resourcesList = new ArrayList<Resources>();
        List<RoleResources> roleResourcesList = roleResourcesRepository.findByRolename(rolename);
        if (roleResourcesList != null && roleResourcesList.size() > 0) {
            for (RoleResources _roleResourcesList : roleResourcesList) {
                if (_roleResourcesList.getResources().getParentid() != 0) {
                    resourcesList.add(_roleResourcesList.getResources());
                } else {
                    List<Resources> _resources = resourcesRepository.findByParentid(_roleResourcesList.getResources().getResourcesid());
                    _roleResourcesList.getResources().setChildren(_resources);
                    resourcesList.add(_roleResourcesList.getResources());
                }
            }
            return resourcesList;
        } else {
            return "该角色名没有资源";
        }


    }


    @Override
    public Object updateRoleResourcesByRolename(String rolename, Integer[] ids) {
        List<RoleResources> roleResourcesList =new ArrayList<RoleResources>();
         roleResourcesList = roleResourcesRepository.findByRolename(rolename);
        if (roleResourcesList != null && roleResourcesList.size() > 0) {
            Integer l = roleResourcesList.get(0).getRoleresourcesid();

            RoleResources list = roleResourcesRepository.findOne(l);

            if (list == null) {
                logger.info("url出错");
                return new Payload("没找到这个id或者url出错");
            }

            Role role = roleResourcesList.get(0).getRole();
            list.setRole(role);

            if (ids != null && ids.length > 0) {
//                if (ids.length == 1) {
//                    list.setResourcesid(ids[0]);
//                    Resources resources = (Resources) resourcesRepository.findOne(ids[0]);
//                    if (resources == null) {
//                        return "id为[" + ids[0] + "]的资源不存在";
//                    } else {
//                        list.setResources(resources);
//                        roleResourcesRepository.save(list);
//                        return 1;
//                    }
//                } else
                    {
                    logger.info("*****" + ids.length);
//                    int j =0;
                    for(RoleResources h:roleResourcesList){
                        Integer s = h.getResourcesid();
                        for (int i = 0; i < ids.length; i++) {
                            if (s == ids[i]){
                                logger.info("*****" + ids[i]+"已经存在");
                                roleResourcesRepository.deleteByResourcesid(s);
                            }
//                            else{
//                                RoleResources roleResources = new RoleResources();
//                                roleResources.setRole(role);
//                                roleResources.setResourcesid(ids[i]);
//                                Resources resources = (Resources) resourcesRepository.findOne(ids[i]);
//                                if (resources == null) {
//                                    return "id为[" + i + "]的资源不存在";
//                                } else {
//                                    roleResources.setResources(resources);
//                                    roleResourcesRepository.save(roleResources);
//                                }
//                            }
                        }

                    }
                    logger.info("----***-----" + ids.length);
                    List<Role> _role = roleRepository.findByRolename(rolename);
                    for (int i = 0; i < ids.length; i++) {
                        RoleResources roleResources = new RoleResources();
                        roleResources.setRole(_role.get(0));
                        roleResources.setResourcesid(ids[i]);
                        Resources resources = (Resources) resourcesRepository.findOne(ids[i]);
                        if (resources == null) {
                            return "id为[" + ids[i] + "]的资源不存在";
                        } else {
                            roleResources.setResources(resources);
                            roleResourcesRepository.save(roleResources);
                        }
                    }

                }
            }
        } else {
            logger.info("---------" + ids.length);
            List<Role> role = roleRepository.findByRolename(rolename);
            for (int i = 0; i < ids.length; i++) {
                RoleResources roleResources = new RoleResources();
                roleResources.setRole(role.get(0));
                roleResources.setResourcesid(ids[i]);
                Resources resources = (Resources) resourcesRepository.findOne(ids[i]);
                if (resources == null) {
                    return "id为[" + ids[i] + "]的资源不存在";
                } else {
                    roleResources.setResources(resources);
                    roleResourcesRepository.save(roleResources);
                }
            }
        }
        return 1;
    }

    }


